import CONST from '../const'

export function filterEmpty (data) {
  if (Array.isArray(data) && data.length > 0) {
    data.forEach(a => {
      if (!Array.isArray(a.children) || a.children.length < 1) {
        a.children = null
      } else {
        filterEmpty(a.children)
      }
    })
  }
}
/**
 *
 * @param {级联选中项数组} val
 * @param {级联数据源} opt
 * @param {关联字段} key
 * @param {查询字段} name
 * @param {子级熟悉名} children
 */
export function getCascader (val, opt, key, name, children) {
  return val.map(function (value, index, array) {
    for (var itm of opt) {
      if (itm[key] === value) { opt = itm[children]; return itm[name] }
    }
    return null
  })
}
/**
   * 将数字转换为两位小数浮点数
   *
   * @param {数字类型} x
   */
export function toDecimal2 (x) {
  let f = parseFloat(x)
  if (isNaN(f)) {
    return false
  }
  f = Math.round(x * 100) / 100
  let s = f.toString()
  let rs = s.indexOf('.')
  if (rs < 0) {
    rs = s.length
    s += '.'
  }
  while (s.length <= rs + 2) {
    s += '0'
  }
  return s
}

export function getDeliveryCompany (code) {
  const company = CONST.DELIVERY_COMPANY.find(c => c.code === code)
  if (company) {
    return company.title
  }
  return ''
}

/**
 * 检测手机号
 * @param {*} mobile 手机号
 */
export function checkMobile (mobile) {
  const reg = /^(((13[0-9]{1})|(14[0-9]{1})|(15[0-9]{1})|(17[0-9]{1})|(18[0-9]{1})|(19[0-9]{1})|(16[0-9]{1}))+\d{8})$/
  return checkReg(mobile, reg)
}
/**
 * 检测中等强度密码
 * @param {*} password 密码
 */
export function checkMiddlePassword (password) {
  const reg = /^(?![a-zA-z]+$)(?!\d+$)(?![!@#$%^&*]+$)[a-zA-Z\d!@#$%^&*]+$/
  return checkReg(password, reg)
}
/**
 * 检验身份
 * @param {*} idCard
 */
export function checkIdcard (idCard) {
  const reg = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/
  return checkReg(idCard, reg)
}
/**
 * 检测正则
 * @param {*} str 文本
 * @param {*} reg 正则
 */
export function checkReg (str, reg) {
  return reg.test(str)
}
